// pages/business/agentreturn/agentreturn.js
var shihan = require('../../../common/fetch');
var config = require('../../../common/config');
var range, currentIndex = 0;
var app = getApp();
var winScale = 750 / app.data.deviceInfo.windowWidth;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mask_flag: false,
    submit_flag: false,
    showLoading: true,
    products: {},
    return_total: 0,
    return_type: 0,//类型 0月度 1年度
    delete_address: 0, //是否删除了地址
    return_type_list: ['月度返货', '年度返货']
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      brand_id: options.id
    })
    wx.setNavigationBarTitle({
      title: options.tit,
    })
    this.getReturnList();
    var windowres = wx.getSystemInfoSync();
    range = range = (windowres.windowHeight / 2) - (270 / winScale) + 600 / winScale;
    var animation = wx.createAnimation({
      duration: 350,
      timingFunction: 'ease-in-out',
    });
    this.animation = animation;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'selectaddresskey',
      success: function (res) {
        that.data.return_result.sh_address = res.data;
        
        that.setData({
          return_result: that.data.return_result
        })
        wx.setStorageSync('return_pic_cache', that.data.return_result);
        wx.removeStorage({
          key: 'selectaddresskey'
        });
      }
    })
    if (that.data.delete_address == 1) {
      that.data.return_result.sh_address = '';
      that.setData({
        return_result: that.data.return_result
      })
    }
  },

  getReturnList: function () {//agent_check_agent_return
    var that = this;
    // brand_id 品牌id 必填 return_type 类型 0月度 1年度
    shihan.sendRequest(config.agent_check_agent_return, 'POST', { brand_id: that.data.brand_id, type: that.data.return_type })
      .then(function (response) {
        if (response.data.code == 0) {
          // console.log(response);
          if (response.data.data.sh_errmsg && response.data.data.sh_errmsg.indexOf('n')>0) {
            response.data.data.sh_errmsg = response.data.data.sh_errmsg.replace(/\\n/g, '\n ');
          }
          if (response.data.data.sh_sys_products && response.data.data.sh_sys_products.length>0) {
            response.data.data.sh_sys_products.forEach(function (el, index) {
              el['sh_qty'] = el.sh_max_qty;
            })
          }
          that.setData({
            return_result: response.data.data
          })
          that.judgeSubmit();
          wx.setStorageSync('return_pic_cache', that.data.return_result);
        }
        that.setData({
          showLoading: false
        })
        wx.stopPullDownRefresh();
      }, function (error) {
        console.log(error);
      });
  },
  judgeSubmit: function () {
    var that = this, num = 0, 
      goods_arr = this.data.return_result.sh_sys_products;
    if (goods_arr && goods_arr.length>0) {
      goods_arr.forEach(function (el, index) {
        num = num + Number(el.sh_qty);
        if (Number(el.sh_qty) > 0) {
          that.data.products[el.sh_id] = el.sh_qty
        } else {
          delete that.data.products[el.sh_id];
        }
      })
      this.setData({
        return_total: num,
        submit_flag: num>0?false:true
      })
    }
  },

  changeReturnType: function (e) {
    var index = e.currentTarget.dataset.index;
    if (currentIndex != index && index == 0) {
      currentIndex = e.currentTarget.dataset.index;
      this.setData({
        return_type: e.currentTarget.dataset.index
      })
      this.getReturnList();
    } 
    if (index == 1) {
      shihan.showToast.call(this, '年度返货正在筹划中，敬请期待');
    }
  },
  openAddress: function (e) { //编辑，添加地址
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/modaddress/modaddress?id=' + id + '&floor=0'
    })
  },
  addGoods: function (e) { //增加数量
    this.calculateQty(e, 'add');
  },
  cutGoods: function (e) { //减少数量
    this.calculateQty(e, 'cut');
  },
  editorGoods: function (e) { //直接输入数量
    this.calculateQty(e, 'editor');
  },
  calculateQty: function (e, kind) { //计算数量 a-收货人索引; b-商品索引
    var that = this,
      product_num = 0,
      b = e.currentTarget.dataset.goods, //商品索引
      list = that.data.return_result; //收货人列表
    if (list.sh_sys_products[b].sh_qty == 0 && kind == 'cut') {
      return false;
    }
    if (list.sh_sys_products[b].sh_qty == list.sh_sys_products[b].sh_max_qty && kind == 'add' && that.data.return_result.sh_is_top_agent==1) {//增加返货数量，只对A级代理商做限制
      shihan.showToast.call(that, '已达到最大返货数量');
      return false;
    }
    if (kind == 'editor') {
      var value = Number(e.detail.value);
      if (value > list.sh_sys_products[b].sh_max_qty && that.data.return_result.sh_is_top_agent == 1) {//增加返货数量，只对A级代理商做限制
        list.sh_sys_products[b].sh_qty = list.sh_sys_products[b].sh_max_qty;
      } else {
        list.sh_sys_products[b].sh_qty = value;
      }
    } else {
      var sh_qty = Number(list.sh_sys_products[b].sh_qty);
      if (kind == 'add') {
        list.sh_sys_products[b].sh_qty = sh_qty + 1;
      } else if (kind == 'cut' && sh_qty > 0) {
        list.sh_sys_products[b].sh_qty = sh_qty - 1;
      }
    }
    that.setData({
      return_result: that.data.return_result
    })
    that.judgeSubmit();
    wx.setStorageSync('return_pic_cache', that.data.return_result);
  },

  agentReturn: function () {
    var that = this, data = {};
    data["type"] = that.data.return_type;
    data["brand_id"] = that.data.brand_id;
    data["address_id"] = that.data.return_result.sh_address.sh_id;
    data["products"] = that.data.products;
    if (!that.data.submit_flag) {
      if (!that.data.return_result.sh_address.sh_id) {
        shihan.showToast.call(that, '请添加收货地址');
        return false;
      }
      
      shihan.sendRequest(config.agent_return_generate, 'POST', data)
        .then(function (response) {
          if (response.data.code == 0) {
            // console.log(response); 
            shihan.showToast.call(that, '返货申请已提交，审核中', 2);
            setTimeout(function () {
              wx.redirectTo({
                url: '/pages/business/management/management'
              })
            }, 2000)
          } else {
            shihan.showToast.call(that, response.data.msg);
          }
        }, function (error) {
          console.log(error);
        });
    }
  },

  lookQuestion: function(e) {
    this.animation.translateY(-range).step();
    this.setData({
      mask_flag: true,
      animationData: this.animation.export()
    })
  },
  closeMask: function () {
    this.animation.translateY(range).step();
    this.setData({
      mask_flag: false,
      animationData: this.animation.export()
    })
  },
  lookReturnList: function () {
    wx.navigateTo({
      url: '/pages/business/management/management'
    })
  },

  returnPolicy: function (e) {
    wx.navigateTo({
      url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + encodeURIComponent(e.currentTarget.dataset.url)
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      showLoading: true
    })
    this.getReturnList();
  }
})